package com.zxj.netty.client;

import com.zxj.netty.component.LoadBalanceService;
import com.zxj.netty.component.impl.RandomLoadBalance;
import io.netty.channel.ChannelFuture;
import org.springframework.util.CollectionUtils;

import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

public class ChannelManager {
    public static final Set<String> SYSTEMS = new HashSet<>();
    // 默认随机负载均衡
    private static LoadBalanceService loadBalanceService = new RandomLoadBalance();
    /**
     * 缓存本地channel
     */
    private static ConcurrentHashMap<String, List<ChannelFuture>>  remoteChannels = new ConcurrentHashMap<>();
    private static AtomicInteger index = new AtomicInteger(0);

    public static void add(String sysAlias, List<ChannelFuture> channelFutures) {
        remoteChannels.put(sysAlias, channelFutures);
    }

    // 轮询获取
    public static ChannelFuture get(String systemAlias) {
        List<ChannelFuture> channelFutures = remoteChannels.get(systemAlias);

        if (CollectionUtils.isEmpty(channelFutures)) {
            throw  new RuntimeException(systemAlias + "未创建连接");
        }

        return loadBalanceService.selectChannel(channelFutures);
    }
}
